const express = require('express');
const router = express.Router();
const { getKnex } = require('../db/knex');
const Result = require('../utils/Result');

// 查询某作品截图列表
router.get('/project/:projectId', async (req, res) => {
  try {
    const knex = getKnex();
    const projectId = req.params.projectId;

    const images = await knex('project_images')
      .where('project_id', projectId)
      .orderBy('order_index', 'asc');

    res.json(Result.success(images));
  } catch (error) {
    console.error(error);
    res.json(Result.fail('获取作品截图失败'));
  }
});

// 新增截图
router.post('/', async (req, res) => {
  try {
    const knex = getKnex();
    const { project_id, image_url, order_index = 0 } = req.body;

    const [id] = await knex('project_images').insert({
      project_id,
      image_url,
      order_index,
    });

    res.json(Result.success({ id }, '截图添加成功'));
  } catch (error) {
    console.error(error);
    res.json(Result.fail('截图添加失败'));
  }
});

// 更新截图
router.put('/:id', async (req, res) => {
  try {
    const knex = getKnex();
    const id = req.params.id;
    const { image_url, order_index } = req.body;

    await knex('project_images').where({ id }).update({ image_url, order_index });
    res.json(Result.success(null, '截图更新成功'));
  } catch (error) {
    console.error(error);
    res.json(Result.fail('截图更新失败'));
  }
});

// 删除截图
router.delete('/:id', async (req, res) => {
  try {
    const knex = getKnex();
    const id = req.params.id;
    await knex('project_images').where({ id }).del();
    res.json(Result.success(null, '截图删除成功'));
  } catch (error) {
    console.error(error);
    res.json(Result.fail('截图删除失败'));
  }
});

module.exports = router;
